import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

const localData = localStorage.getItem('Menu')
export const useMenuStore = defineStore('Menu', {
    // state 是 store 的数据 (data)
    // getters 是 store 的计算属性 (computed)
    // actions 则是方法 (methods)。
    state: () => ({
        isCollapsed: localData?localData.isCollapsed:false,
        selectMenu: localData?localData.selectMenu:[],
        routerList:localData?localData.routerList:[],
        menuActive:'1-1'

    }),
    actions: {
        //控制菜单收起和展开
        collapsedMenu(){
            this.isCollapsed = !this.isCollapsed;
            //return this.isCollapsed;
        },
        //显示所选的菜单
        addMenu(payLoad){
            //判断是否存在
            if(this.selectMenu.findIndex(item => item.path === payLoad.path)===-1 ){
                this.selectMenu.push(payLoad);
            }
        },
        //删除所选的菜单
        removeMenu(payLoad){
            this.selectMenu.splice(this.selectMenu.findIndex(item => item.path === payLoad.path),1);
        },
        //动态菜单
        dynamicMenu(payLoad){
            //获取文件路径
            const modules = import.meta.glob('../views/**/**/*.vue');
            //匹配 路由
            function matchRoute(routers) {
                routers.forEach(router => {
                    // 修正 path 字段
                    if (router.path && router.path.startsWith('/')) {
                        router.path = router.path.slice(1)
                    }
                    // 动态添加 component
                    if (!router.children) {
                        const path = router.meta.path.startsWith('/')
                            ? router.meta.path.slice(1)
                            : router.meta.path
                        const url = `../views/${path}/index.vue`
                        router.component = modules[url]
                    } else {
                        matchRoute(router.children)
                    }
                })
            }
            matchRoute(payLoad)
            this.routerList=payLoad;

        },
        //更新高亮数据
        updateMenuActive(payLoad){
            this.menuActive=payLoad;
        }

    },
    persist: true
});

